package com.ds.infra.rpc.annotation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;

/**
 * 作用：处理@EnableRpc的扫描逻辑
 * 在 @EnableRpc 被触发时执行，仅负责包路径扫描（不处理具体注解逻辑），由 @EnableRpc 的 @Import 直接管理
 *
 * @author WeiShaoying
 */
@Slf4j
public class RpcComponentScannerRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 1. 解析@EnableRpc注解属性
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(
                importingClassMetadata.getAnnotationAttributes(EnableRpc.class.getName()));

        // 2. 配置包扫描路径（默认启动类所在包）
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false);
        if (attributes != null) {
            String[] basePackages = attributes.getStringArray("scanBasePackages");
            if (basePackages.length == 0) {
                basePackages = new String[]{
                        ((StandardAnnotationMetadata) importingClassMetadata).getIntrospectedClass().getPackage().getName()
                };
            }
            int beanCount = scanner.scan(basePackages);
            log.info("====扫描{}包含{}个Rpc组件", basePackages, beanCount);
        }
    }
}
